#!/bin/sh

# @file sprout.monit
#
# Copyright (C) Metaswitch Networks 2016
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.

# Set up the monit configuration for sprout with the right IP addresses and ports
cat > /etc/monit/conf.d/sprout.monit <<EOF
# Check the Sprout process.

# Monitor the service's PID file and memory use.
check process sprout_process with pidfile /var/run/sprout/sprout.pid
  group sprout

  # The start, stop and restart commands are linked to alarms
  start program = "/bin/bash -c '/usr/share/clearwater/infrastructure/monit_stability/sprout-stability reset; /usr/share/clearwater/bin/issue-alarm monit 1000.3; /etc/init.d/sprout start'"
  stop program = "/bin/bash -c '/usr/share/clearwater/bin/issue-alarm monit 1000.3; /etc/init.d/sprout stop'"
  restart program = "/bin/bash -c '/usr/share/clearwater/infrastructure/monit_stability/sprout-stability reset; /usr/share/clearwater/bin/issue-alarm monit 1000.3; /etc/init.d/sprout restart'"

  # Check the service's resource usage, and abort the process if it's too high. This will
  # generate a core file and trigger diagnostics collection.
  if memory > 80% then exec "/bin/bash -c '/usr/share/clearwater/infrastructure/monit_stability/sprout-stability aborted; /usr/share/clearwater/bin/issue-alarm monit 1000.3; /etc/init.d/sprout abort'"

# Clear any alarms if the process has been running long enough.
check program sprout_uptime with path /usr/share/clearwater/infrastructure/monit_uptime/check-sprout-uptime
  group sprout
  depends on sprout_process
  every 3 cycles
  if status != 0 then alert

# Check the SIP/HTTP interfaces. These depend on the Sprout process (and so won't run
# unless the Sprout process is running)
check program poll_sprout_sip with path "/usr/share/clearwater/bin/poll_sprout_sip.sh"
  group sprout
  depends on sprout_process

  # Aborting generates a core file and triggers diagnostic collection.
  if status != 0 for 2 cycles then exec "/bin/bash -c '/usr/share/clearwater/infrastructure/monit_stability/sprout-stability aborted; /usr/share/clearwater/bin/issue-alarm monit 1000.3; /etc/init.d/sprout abort'"

check program poll_sprout_http with path "/usr/share/clearwater/bin/poll_sprout_http.sh"
  group sprout
  depends on sprout_process

  # Aborting generates a core file and triggers diagnostic collection.
  if status != 0 for 2 cycles then exec "/bin/bash -c '/usr/share/clearwater/infrastructure/monit_stability/sprout-stability aborted; /usr/share/clearwater/bin/issue-alarm monit 1000.3; /etc/init.d/sprout abort'"
EOF
chmod 0644 /etc/monit/conf.d/sprout.monit

# Force monit to reload its configuration
reload clearwater-monit &> /dev/null || true
